package com.lqg.bookLibrary.config;

import com.lqg.bookLibrary.common.securityImpl.*;
import com.lqg.bookLibrary.service.impl.LoginUserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.annotation.Resource;

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    // 权限不足拦截器
    @Autowired
    private AccessDeniedHandler accessDeniedHandler;


    /**
     * 未登录响应
     * */
    @Resource
    private CustomizeAuthenticationEntryPoint authenticationEntryPoint;

    /**
     * 登录成功响应
     * */
    @Resource
    private AuthenticationSuccessHandlerImpl authenticationSuccessHandler;

    /**
     * 登录失败响应
     * */
    @Resource
    private AuthenticationFailureHandler authenticationFailureHandler;

    /**
     * 登出响应
     * */
    @Resource
    private LogoutSuccessHandlerImpl logoutSuccessHandler;

    /**
     * 解决 无法直接注入 AuthenticationManager
     *
     * @return
     * @throws Exception
     */
    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception
    {
        return super.authenticationManagerBean();
    }

    @Bean
    JwtAuthenticationFilter jwtAuthenticationFilter(){
        JwtAuthenticationFilter jwtAuthenticationFilter =
                new JwtAuthenticationFilter(new AuthenticationManager() {
                    @Override
                    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
                        return null;
                    }
                });
        return jwtAuthenticationFilter;
    }
    /**
     * 自定义用户认证逻辑
     */
    @Autowired
    private LoginUserServiceImpl loginUserService;

    /** 授权 */
    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception{

        httpSecurity
                .cors()  //跨域配置
                .and()
                .csrf().disable()

                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)

                .and()
                .authorizeRequests()
                //.antMatchers("/user/**").hasRole("b")
                //.antMatchers("/admin/**").hasRole("a")
                .anyRequest().permitAll()
                //.anyRequest().anonymous()

                .and()
                .exceptionHandling()
                //匿名用户访问无权限资源时的异常处理
                .authenticationEntryPoint(authenticationEntryPoint)
                .accessDeniedHandler(accessDeniedHandler)

                ////自定义username的传值形式,前端获取时name为此值
                //.and()
                //.formLogin()
                //.loginProcessingUrl("/user/login")
                //.usernameParameter("username")
                //.successHandler(authenticationSuccessHandler)
                //.failureHandler(authenticationFailureHandler)

                .and()
                .logout()
                .permitAll()
                .logoutSuccessHandler(logoutSuccessHandler)
                //登出删除cookies
                .deleteCookies("JSESSIONID")

                .and()
                .rememberMe()

                .and()
                .addFilter(jwtAuthenticationFilter())
        ;

        // 将loginFilter过滤器添加到UsernamePasswordAuthenticationFilter过滤器所在的位置
        httpSecurity.addFilterAt(myUsernamePasswordFilter(), UsernamePasswordAuthenticationFilter.class);

    }


    /**
     * 强散列哈希加密实现
     */
    @Bean
    public PasswordEncoder bCryptPasswordEncoder()
    {
        return new BCryptPasswordEncoder();
    }

    /**
     * 身份认证接口
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(loginUserService).passwordEncoder(bCryptPasswordEncoder());
    }

    @Bean
    public MyUsernamePasswordFilter myUsernamePasswordFilter() throws Exception {
        MyUsernamePasswordFilter loginFilter = new MyUsernamePasswordFilter();
        loginFilter.setFilterProcessesUrl("/user/login");
        loginFilter.setUsernameParameter("username");
        loginFilter.setPasswordParameter("password");
        loginFilter.setAuthenticationManager(authenticationManager());
        loginFilter.setAuthenticationSuccessHandler(authenticationSuccessHandler);
        loginFilter.setAuthenticationFailureHandler(authenticationFailureHandler);
        return loginFilter;
    }

}
